// 商品管理

var router = require('koa-router')(),
    DB = require('../../module/db.js');

/**
 * @router POST /admin/goods/categories
 * @desc   获取商品分类添加接口地址  返回数据
 */    
router.get('/categories' , async (ctx) => { 
    let data = await DB.find('categories')
    let arr = [];
    
    function tree(data) {
        var map = {};
        data.forEach(function (item) {
            map[item.cat_id] = item;       
        });
        var val = [];
        data.forEach(function (item) {
            var parent = map[item.cat_pid];      //这里是父级ID---pid
            if (parent) {
                (parent.children || (parent.children = [])).push(item);
            } else {
                arr.push(item);
            }
        });
        return val;
    }
    tree(data)
    try {
        
        ctx.body = {
            status: 200,
            categories : arr
        }
    } catch (error) {
        ctx.body = {
            status: 404,
            msg: "获取失败"
        }
    }
})
/**
 * @router POST /admin/goods/categoriesDelete
 * @desc   获取商品分类删除接口地址  返回数据
 */  
router.post ('/categoriesDelete' , async (ctx) => {
    let id = ctx.request.body.id;
    if (id) {
        let data = await DB.remove('categories',{"_id":DB.getObjectId(id)});
        try{
            if (data.result.ok) {
                ctx.body = {
                    code: 1,
                    status: 200,
                    msg:"删除成功"
                }
            }
        }catch (err) {
            ctx.body = {
                code: 20,
                status: 404,
                msg:"删除失败"
            }
            return;
        }
    }
} )
/**
 * @router POST /admin/goods/categoriesadd
 * @desc   获取商品分类添加  返回数据
 */  
router.post ('/categoriesAdd' , async (ctx) => {
    const categories = ctx.request.body;
    //先查询数据类名是否存在
    let  data = await DB.find('categories',{"cat_name":categories.cat_name})
    if(data[0]){
        ctx.body = {
            code: 10,
            status: 1000,
            msg:"类名已存在"
        }
        return false
    }
    try{
        let userEdit = await DB.insert('categories',{"cat_id":categories.cat_id, "cat_name" : categories.cat_name , "cat_pid" : categories.cat_pid , "cat_lever" : categories.cat_lever });
        if(userEdit.result.ok){
            ctx.body = {
                code: 1,
                status: 200,
                msg:"添加成功"
            }
        }
        return
    }catch(err){
        ctx.body = {
            code: 40,
            status: 404,
            msg:"网络错误"
        }
    } 
} )
module.exports = router.routes(); 